<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\command\Project;

use app\common\library\WechatPay;
use app\common\manager\assistant\AssistantAccountManager;
use app\common\manager\UserAccountManager;
use app\common\model\assistant\Withdraw;
use app\common\model\PayLog;
use app\common\model\Transferrecord;
use app\common\model\Withdrawrecord;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class Query extends Command
{
    protected $model = null;

    protected function configure()
    {
        $this->setName('query')
            ->setDescription('task');
        //要执行的controller必须一样，不适用模糊查询
    }

    protected function execute(Input $input, Output $output)
    {
        $page = 1;
        $step = 100;
        $wechatPay = new WechatPay();
        while (true){
            $start = ($page-1)*$step;
            $data = Transferrecord::where('status',Transferrecord::STATUS_SEND)->limit($start,$step)->select();
            if ($data){
                foreach ($data as $k=>$v){
                    $response = $wechatPay->queryBatchTransfer($v->batch_no);
                    if ($response['code'] != $wechatPay->successCode){
                        continue;
                    }
                    print_r($response);
                    if (!empty($response['data']) && !empty($response['data']['transfer_batch']) && !empty($response['data']['transfer_detail_list'])){
                        PayLog::where('order',$v->order)->update(['response'=>serialize($response['data']),'response_code'=>$response['data']['transfer_batch']['batch_status'],'processed'=>1,'update_time'=>time()]);
                        foreach ($response['data']['transfer_detail_list'] as $k=>$v){
                            Db::startTrans();
                            try {
                                if (!$transferInfo = Transferrecord::where('detail_no',$v['out_detail_no'])->where('status',Transferrecord::STATUS_SEND)->find()){
                                    throw new Exception('转账记录不存在');
                                }

                                if ($transferInfo['status'] == Transferrecord::STATUS_SUCCESS){
                                    throw new Exception('当前记录已处理');
                                }
                                //  FAIL  WAIT_PAY PROCESSING SUCCESS
                                if ($v['detail_status'] == 'SUCCESS'){

                                    if(!Transferrecord::where('id',$transferInfo['id'])->where('status','<>',Transferrecord::STATUS_SUCCESS)->update([
                                        'status' => Transferrecord::STATUS_SUCCESS,
                                        'update_time'=>time()
                                    ])){
                                        throw new Exception('更改转账记录失败');
                                    }

                                    if ($transferInfo['relation_id']){

                                        if ($transferInfo['detail'] == Transferrecord::DETAIL_USER){
                                            $withdrawInfo = Withdrawrecord::where('id',$transferInfo['relation_id'])->find();
                                            if (!$withdrawInfo){
                                                throw new Exception('提现记录不存在');
                                            }

                                            if (!Withdrawrecord::where('id',$transferInfo['relation_id'])->where('status','<>',Withdrawrecord::STATUS_SUCCESS)->update([
                                                'status' => Withdrawrecord::STATUS_SUCCESS,
                                                'third_order' => $v['detail_id'],
                                                'update_time' => time(),
                                            ])){
                                                throw new Exception('提现记录更新失败');
                                            }

                                            $result = UserAccountManager::money($withdrawInfo['user_id'],$withdrawInfo['amount'],UserAccountManager::CHANGE_TYPE_PAYMENT,$withdrawInfo['create_time'],UserAccountManager::TYPE_WITHDRAWAL,['relation_id'=>$withdrawInfo['id'],'relation_order'=>$withdrawInfo['order']],false);
                                            print_r($result);
                                            if ($result['code'] != UserAccountManager::$successCode){
                                                throw new Exception($result['message']);
                                            }
                                        }else if ($transferInfo['detail'] == Transferrecord::DETAIL_ASSISTANT){
                                            $assistantWithdrawInfo = Withdraw::where('id',$transferInfo['relation_id'])->find();
                                            if (!$assistantWithdrawInfo){
                                                throw new Exception('助教提现记录不存在');
                                            }

                                            if (!Withdraw::where('id',$transferInfo['relation_id'])->where('status','<>',Withdrawrecord::STATUS_SUCCESS)->update([
                                                'status' => Withdraw::STATUS_SUCCESS,
                                                'third_order' => $v['detail_id'],
                                                'update_time' => time(),
                                            ])){
                                                throw new Exception('助教提现记录更新失败');
                                            }

                                            $result = AssistantAccountManager::money($assistantWithdrawInfo['assistant_id'],$assistantWithdrawInfo['user_id'],$assistantWithdrawInfo['amount'],AssistantAccountManager::CHANGE_TYPE_PAYMENT,$assistantWithdrawInfo['create_time'],AssistantAccountManager::TYPE_WITHDRAWAL,['relation_id'=>$assistantWithdrawInfo['id'],'relation_order'=>$assistantWithdrawInfo['order']],false);
                                            print_r($result);
                                            if ($result['code'] != AssistantAccountManager::$successCode){
                                                throw new Exception($result['message']);
                                            }
                                        }



                                    }

                                }else if ($v['detail_status'] == 'FAIL'){
                                    if(!Transferrecord::where('id',$transferInfo['id'])->where('status','<>',Transferrecord::STATUS_SUCCESS)->update([
                                        'status' => Transferrecord::STATUS_FAIL,
                                        'update_time'=>time()
                                    ])){
                                        throw new Exception('更改转账记录失败');
                                    }

                                    if ($transferInfo['relation_id']){

                                        if ($transferInfo['detail'] == Transferrecord::DETAIL_USER){
                                            $withdrawInfo = Withdrawrecord::where('id',$transferInfo['relation_id'])->find();
                                            if (!$withdrawInfo){
                                                throw new Exception('提现记录不存在');
                                            }

                                            if (!Withdrawrecord::where('id',$transferInfo['relation_id'])->where('status','<>',Withdrawrecord::STATUS_BACK)->update([
                                                'status' => Withdrawrecord::STATUS_BACK,
                                                'third_order' => $v['detail_id'],
                                                'update_time' => time(),
                                            ])){
                                                throw new Exception('提现记录更新失败');
                                            }

                                            $result = UserAccountManager::money($withdrawInfo['user_id'],$withdrawInfo['amount'],0,$withdrawInfo['create_time'],UserAccountManager::TYPE_FREEZE_RETURN,['relation_id'=>$withdrawInfo['id'],'relation_order'=>$withdrawInfo['order']]);
                                            if ($result['code'] != UserAccountManager::$successCode){
                                                throw new Exception('账户变动失败');
                                            }
                                        }else if ($transferInfo['detail'] == Transferrecord::DETAIL_ASSISTANT){
                                            $assistantWithdrawInfo = Withdraw::where('id',$transferInfo['relation_id'])->find();
                                            if (!$assistantWithdrawInfo){
                                                throw new Exception('助教提现记录不存在');
                                            }

                                            if (!Withdraw::where('id',$transferInfo['relation_id'])->where('status','<>',Withdraw::STATUS_BACK)->update([
                                                'status' => Withdraw::STATUS_BACK,
                                                'third_order' => $v['detail_id'],
                                                'update_time' => time(),
                                            ])){
                                                throw new Exception('助教提现记录更新失败');
                                            }

                                            $result = AssistantAccountManager::money($assistantWithdrawInfo['assistant_id'],$assistantWithdrawInfo['user_id'],$assistantWithdrawInfo['amount'],0,$assistantWithdrawInfo['create_time'],AssistantAccountManager::TYPE_FREEZE_RETURN,['relation_id'=>$assistantWithdrawInfo['id'],'relation_order'=>$assistantWithdrawInfo['order']],false);
                                            if ($result['code'] != AssistantAccountManager::$successCode){
                                                throw new Exception('助教账户变动失败');
                                            }
                                        }

                                    }
                                }

                                Db::commit();

                            }catch (Exception $e){
                                Db::rollback();
                                echo $e->getMessage();
                                continue;
                            }
                        }
                    }
                }
            }
            sleep(10);
        }
    }

}
